<?php

namespace app\store\service;

use app\store\model\SpikeGoods;
use think\facade\Db;

class SpikeGoodsService
{
    /**
     *
     * 获取秒杀商品列表
     * */
    public function getSpikeGoodsList($param)
    {   
        $store_id = session('store_id');

        $query = Db::name('spike_goods')
                   ->field('a.id,a.sort,a.sell_price,a.spike_price,a.spike_stock,a.total_sale,a.status,a.create_time,a.update_time,
                   b.goods_name,b.main_image')
                   ->alias('a')
                   ->join('goods b','a.goods_id=b.id')
                   ->where('a.store_id',$store_id);


        if(isset($param['status']) and $param['status'] != ''){
            $query->where('a.status',$param['status']);
        }

        if(!empty($param['keyword'])){
            $query->whereLike('b.goods_name',"%{$param['keyword']}%");
        }

        $goods = $query->order('a.id','desc')->paginate(10);

        return $goods;
    }

    public function getSpikeGoodsOptions($param)
    {   
        $store_id = session('store_id');

        if(isset($param['ids'])){
            $idArr = json_decode($param['ids'],true);
        }

        $query = Db::name('spike_goods')
                   ->field('a.id,a.spike_price,a.spike_stock,a.create_time,b.goods_name,b.main_image,b.sell_price')
                   ->alias('a')
                   ->join('goods b','a.goods_id=b.id')
                   ->where(['a.store_id' => $store_id,'a.status' => 1]);

        if(!empty($idArr)){
            $query->whereNotIn('a.id',$idArr);
        }

        if(!empty($param['cid'])){
            $query->where('b.category_id',$param['cid']);
        }

        if(!empty($param['keyword'])){
            $query->whereLike('b.goods_name',"%{$param['keyword']}%");
        }
     
        $spikeGoodsOptions = $query->paginate(10);

        return $spikeGoodsOptions;
    }


    /**
     * 获取秒杀商品详情
     * */
    public function findSpikeGoods($id)
    {
        $model = new  SpikeGoods();
        $goods = $model->withoutField('create_time,update_time,delete_time')
                        ->with(['items','goods','goodsItems'])
                        ->where('id',$id)->find();


        $arr =  $goods->toArray();
        $old = $arr['goodsItems'];
        $new = $arr['items'];
        $item = [];
        foreach ($new as $k => $v){
            $item[$k]['attr'] = $old[$k]['attr'];
            $item[$k]['image'] = $old[$k]['image'];
            $item[$k]['sell_price'] = $old[$k]['sell_price'];
            $item[$k]['id'] = $v['id'];
            $item[$k]['sku_id'] = $v['sku_id'];
            $item[$k]['spike_price'] = $v['spike_price'];
            $item[$k]['spike_stock'] = $v['spike_stock'];
        }

        $goods['items'] = $item;
     
        return $goods;
    }

    /**
     * 添加秒杀商品
     * */
    public function saveSpikeGoods($data)
    {
        $data['store_id'] = session('store_id');

        if ($data['spec_type'] == 2){
            $skus = [];
            $this->formatGoodsInfo($data,$skus);
            $goods =  SpikeGoods::create($data);
            $goods->items()->saveAll($skus);
            return  $goods['id'];
        }
        $goods =  SpikeGoods::create($data);

        return $goods['id'];
    }


    /**
     * 更新秒杀商品
     * */
    public function updateSpikeGoods($data)
    {
        if ($data['spec_type'] == 2){
            $skus = [];
            $this->formatGoodsInfo($data,$skus);
            $goods =  SpikeGoods::update($data);
            $goods->items()->saveAll($skus);
            return  $goods['id'];
        }

        $goods =  SpikeGoods::update($data);

        return $goods['id'];
    }

    /**
     * 格式化商品信息
     * */
    protected function formatGoodsInfo(&$data,$isUpdate=false)
    {
        $arr = json_decode($data['skus'], true);
        $skus = [];

        if ($isUpdate){
            foreach ($arr as $k => $v){
                $skus[$k]['id'] = $v['id'];
                $skus[$k]['sku_id'] = $v['sku_id'];
                $skus[$k]['spike_stock'] = $v['spike_stock'];
                $skus[$k]['spike_price'] = $v['spike_price'];
            }
        } else {
            foreach ($arr as $k => $v){
                $skus[$k]['sku_id'] = $v['id'];
                $skus[$k]['spike_stock'] = $v['spike_stock'];
                $skus[$k]['spike_price'] = $v['spike_price'];
            }
        }

        $data['spike_price'] = min(array_column($skus,'spike_price'));
        $data['spike_stock'] =  array_sum(array_column($skus,'spike_stock'));
    }



}